package com.fish.gaiety.gateway.service.impl;

import com.fish.gaiety.gateway.entity.UserApi;
import com.fish.gaiety.gateway.entity.dto.User;
import com.fish.gaiety.gateway.repository.UserRepository;
import com.fish.gaiety.gateway.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

/**
 * @author Jerry
 * @date 2022/9/30
 * @description User service Impl
 */
@Component
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public Stream<User> findAll() {
        return userRepository.findAll().stream();
    }

    @Override
    public User create(User user) {
        return userRepository.save(user);
    }

    @Override
    public User update(User user) {
        return userRepository.save(user);
    }

    @Override
    public User delete(Long id) {
        var user = userRepository.findById(id);
        user.ifPresent(userRepository::delete);
        return user.orElseThrow(()->new SecurityException("删除错误"));
    }

    @Override
    public User toEntity(UserApi userApi) {
        return userApi.toUser();
    }

    @Override
    public UserApi toAPI(User user) {
        return new UserApi(user);
    }
}
